package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

@SuppressWarnings("unchecked")
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration){
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml文件
     */
    public void parse(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selects = rootElement.selectNodes("select|insert|delete|update");
        setMappedStatement(namespace,selects);
    }

    private void setMappedStatement(String namespace, List<Element> selects) throws Exception {
        for (Element select : selects) {
            String id = select.attributeValue("id");
            String sqlText = select.getTextTrim();
            String sqlCommandType = select.getQName().getName(); // sql类型
            Class<?> paramterType = getClassType(select.attributeValue("paramterType"));
            Class<?> resultType = getClassType(select.attributeValue("resultType"));
            String useCache = select.attributeValue("useCache");
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setNamespace(namespace);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlCommandType(sqlCommandType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            // 设置二级缓存
            if (configuration.getCacheEnabled()){
                configuration.getStatementCache().put(namespace, new HashMap<>());
                // 设置二级缓存刷新规则
                if(useCache != null){
                    mappedStatement.setUseCache(Boolean.valueOf(useCache));
                }
            }
            String statementId = new StringBuilder(namespace).append(".").append(id).toString();
            configuration.getMappedStatements().put(statementId, mappedStatement);
        }
    }

    private Class<?> getClassType (String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            return Class.forName(paramterType);
        }
        return null;
    }
}
